package base.thread_JUC.demo05;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * SynchronousQueue 同步阻塞队列演示
 * 不存储元素，或者说存一个取一个，也即单个元素的队列.
 *
 * 同步的生产-》消费轮询
 * t1	 put 1
 * t2	 get 1
 * t1	 put 2
 * t2	 get 2
 * t1	 put 3
 * t2	 get 3
 *
 */
public class SynchronousQueueTest {
    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new SynchronousQueue<>();

        // t1线程负责存
        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName()+"\t put 1");
                blockingQueue.put("1");

                System.out.println(Thread.currentThread().getName()+"\t put 2");
                blockingQueue.put("2");

                System.out.println(Thread.currentThread().getName()+"\t put 3");
                blockingQueue.put("3");
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }, "t1").start();


        // t2线程负责取
        new Thread(()->{
            try {
                // 故意延时2s再去获取
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName()+"\t get "+blockingQueue.take());

                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName()+"\t get "+blockingQueue.take());

                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName()+"\t get "+blockingQueue.take());
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }, "t2").start();
    }
}
